package com.proton.carepatchtemp.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.adapter.DeviceAdapter;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.ui.WaveView;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;

public class SearchDevicesActivity extends BaseActivity {

    private static final int REQUEST_CODE_REQUEST_PERMISSION = 1;
    private static int REQUEST_ENABLE_BT = 1;
    public List deviceList = new ArrayList();
    ImageButton mBtnBack;
    RecyclerView mRcvFindDevices;
    WaveView mWave;
    ImageView mSearchImage;
    LinearLayout mActivitySearchDevices;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private DeviceAdapter mDeviceAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private boolean mScanning;
    private LinearLayout mLnlSearchTips;

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.BT_SCAN_A_DVC:
                deviceList.add(event.getObj());
                mDeviceAdapter.notifyDataSetChanged();
                mLnlSearchTips.setVisibility(View.INVISIBLE);
                break;
            case Codes.PRF_GO_CHOOSE_PRF:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_devices);

        initView();
        initBluetooth();
        setListener();
    }

    private void initView() {
        mBtnBack = findViewById(R.id.btn_back);
        mRcvFindDevices = findViewById(R.id.rcv_find_devices);
        mWave = findViewById(R.id.wave);
        mSearchImage = findViewById(R.id.search_image);
        mActivitySearchDevices = findViewById(R.id.activity_search_devices);
        mHandler = new Handler();
        mDeviceAdapter = new DeviceAdapter(deviceList, this);
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRcvFindDevices.setLayoutManager(mLinearLayoutManager);
        mRcvFindDevices.setAdapter(mDeviceAdapter);
        mLnlSearchTips = findViewById(R.id.lnl_search_tips);
    }

    @Override
    public void setListener() {
        mSearchImage.setOnClickListener(view -> {
            mSearchImage.setEnabled(false);
            deviceList.clear();
            mLnlSearchTips.setVisibility(View.VISIBLE);
            scanLeDevice(true);
            mDeviceAdapter.notifyDataSetChanged();
        });

        mBtnBack.setOnClickListener(view -> {
            scanLeDevice(false);
            finish();
        });
    }


    public void initBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(VCare.get(), R.string.ble_not_supported, Toast.LENGTH_LONG).show();
            LogUtils.e(R.string.ble_not_supported);
        }
        //蓝牙是否运作，为否的话进行请求
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        mBluetoothAdapter.enable();
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(() -> {
                mScanning = false;
                stopWave(mWave);
                mSearchImage.setEnabled(true);
            }, Settings.SEARCH_TIME);
            startWave(mWave);
            mScanning = true;
            EventBus.getDefault().post(new MainEvent(Codes.BT_START_SEARCH_DEVICE));
        } else {
            mScanning = false;
            stopWave(mWave);
        }
    }

    public void startWave(WaveView wave) {
        wave.setDuration(5000);
        wave.setStyle(Paint.Style.FILL);
        wave.setColor(ContextCompat.getColor(this, R.color.blueCenter));
        wave.setInterpolator(new LinearOutSlowInInterpolator());
        wave.setInitialRadius(120);
        wave.setMaxRadius(336);
        wave.start();
    }

    public void stopWave(WaveView wave) {
        wave.stop();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mScanning) {
            scanLeDevice(false);
        }
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_REQUEST_PERMISSION) {
            if (RESULT_OK == resultCode) {
                Log.e(TAG, getString(R.string.string_get) + " " + requestCode + " " + getString(R.string.string_success));
            } else {
                Log.e(TAG, getString(R.string.string_get) + " " + requestCode + " " + getString(R.string.string_fail));
            }
        }
    }
}
